package com.xszx.servlet.user.order;

import com.xszx.bean.Address;
import com.xszx.bean.Order;
import com.xszx.bean.dto.CartDto;
import com.xszx.bean.dto.OrderDto;
import com.xszx.dao.AddressDao;
import com.xszx.dao.CartDao;
import com.xszx.dao.OrderDao;
import com.xszx.dao.UserDao;
import com.xszx.dao.impl.AddressDaoImpl;
import com.xszx.dao.impl.CartDaoImpl;
import com.xszx.dao.impl.OrderDaoImpl;
import com.xszx.dao.impl.UserDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@WebServlet("/AddOrderServlet")
public class AddOrderServlet extends HttpServlet {
    static OrderDao orderDao = new OrderDaoImpl();
    static CartDao cartDao = new CartDaoImpl();
    static UserDao userDao = new UserDaoImpl();
    static AddressDao addressDao = new AddressDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        String username = req.getSession().getAttribute("username").toString();
        if (!username.equals("tourist")) {
            Integer userId = userDao.getUserIdByUsername(username);
            List<CartDto> cartDto = cartDao.getCartsByUserId(userId);
            List<Address> allAddress = addressDao.getAllAddress(userId);
            String seq = UUID.randomUUID().toString().substring(18);
            for (CartDto cart : cartDto) {
                Order order = new Order(seq, cart.getGoodsId(), cart.getGoodsName(), cart.getGoodsCount(), cart.getGoodsPrice(), cart.getUserId(), allAddress.get(0).getConName(), allAddress.get(0).getConPhone());
                orderDao.addOrder(order);
            }
            //删除购物车相关商品
            cartDao.deleteCartByUserId(userId);

            req.getRequestDispatcher("GetOrdersServlet").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
